package com.jz.yanshe.dialog;

import android.app.Dialog;
import android.graphics.Canvas;
import android.graphics.Rect;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.jz.jd.rest.business.RestProxy;
import com.jz.jd.rest.exception.BusinessException;
import com.jz.jd.rest.response.BaseResponse;
import com.jz.jd.rest.response.StyleResponse;

import java.util.ArrayList;
import java.util.List;

import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;
import com.jz.yanshe.base.BaseDialogFragment;
import com.jz.yanshe.util.ImageLoaderHelper;
import com.jz.yanshe.adapter.TypeAdapter;
import jz.com.feierman.R;

import com.jz.yanshe.base.BaseActivity;
import com.jz.yanshe.util.PreferencesHelper;

/**
 * Created by Administrator on 2018/3/1.
 */

public class BuyDialog extends BaseDialogFragment implements View.OnClickListener {

    public static BuyDialog newInstance() {
        return new BuyDialog();
    }

    private OnItemClickListener mListener;

    private Dialog mDialog;
    private TextView btn_confirm;

    RecyclerView recyclerViewSize;
    RecyclerView recyclerViewColor;

    TypeAdapter adapterColor;
    TypeAdapter adapterSize;

    List<StyleResponse.Sizes> listSize = new ArrayList<>();
    List<StyleResponse.Sizes> listColor = new ArrayList<>();

    TextView btn_plus, btn_minus, tv_size,tv_goods_num, tv_price, tv_remain;

    ImageView img_goods;

    public String goodsid;
    public String url;
    public String price;
    public String remain;

    public String style_color;


    @Override
    public void onClick(View v) {

        switch (v.getId()) {
            case R.id.btn_plus:
                tv_goods_num.setText((Integer.valueOf(tv_goods_num.getText().toString().trim()) + 1) + "");
                break;
            case R.id.btn_minus:
                if (Integer.valueOf(tv_goods_num.getText().toString().trim()) > 1) {
                    tv_goods_num.setText((Integer.valueOf(tv_goods_num.getText().toString().trim()) - 1) + "");
                }
                break;
            case R.id.btn_confirm: {

                for (int j = 0; j < listColor.size(); j++) {
                    if (listColor.get(j).select == 1) {
                        addShoppingCar(listColor.get(j).goods_style_id, tv_goods_num.getText().toString().trim());
                    }
                }
                break;
            }
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.dialog_buy, container);
        view.findViewById(R.id.btn_confirm).setOnClickListener(this);
        view.findViewById(R.id.btn_minus).setOnClickListener(this);
        view.findViewById(R.id.btn_plus).setOnClickListener(this);
        tv_goods_num = view.findViewById(R.id.tv_goods_num);
        tv_price = view.findViewById(R.id.tv_price);
        tv_remain = view.findViewById(R.id.tv_remain);
        tv_size = view.findViewById(R.id.tv_size);
        img_goods = view.findViewById(R.id.img_goods);
        adapterColor = new TypeAdapter(getContext(), listColor);
        adapterSize = new TypeAdapter(getContext(), listSize);
        recyclerViewColor = view.findViewById(R.id.recyclerViewColor);
        recyclerViewSize = view.findViewById(R.id.recyclerViewSize);


        LinearLayoutManager manager1 = new LinearLayoutManager(getActivity());
        LinearLayoutManager manager2 = new LinearLayoutManager(getActivity());
        manager1.setOrientation(LinearLayoutManager.HORIZONTAL);
        manager2.setOrientation(LinearLayoutManager.HORIZONTAL);
        recyclerViewColor.setLayoutManager(manager1);
        recyclerViewSize.setLayoutManager(manager2);
        recyclerViewColor.setAdapter(adapterColor);
        recyclerViewSize.setAdapter(adapterSize);
        adapterSize.onItemClick = new TypeAdapter.OnItemClick() {

            @Override
            public void onItemClick(String style_color) {
                queryGoodsId(style_color);
                BuyDialog.this.style_color = style_color;
                tv_size.setText("已选： "+ style_color );
            }

            @Override
            public void onItemClick() {

            }
        };
        adapterColor.onItemClick = new TypeAdapter.OnItemClick() {
            @Override
            public void onItemClick(String style_color) {
                for (int i = 0; i < listColor.size(); i++) {
                    if (listColor.get(i).select == 1) {
                        if(TextUtils.isEmpty(listColor.get(i).style_icon)){
                            ImageLoaderHelper.getInstance().GlideImageLoader(getActivity(), listColor.get(i).goods_icon, img_goods);
                        }else {
                            ImageLoaderHelper.getInstance().GlideImageLoader(getActivity(), listColor.get(i).style_icon, img_goods);
                        }
                        tv_price.setText("¥ " + listColor.get(i).style_price);
                        tv_remain.setText("库存" + listColor.get(i).goods_inventory + "件");
                        tv_size.setText("已选： "+ BuyDialog.this.style_color + "   "+style_color);
                    }
                }
            }

            @Override
            public void onItemClick() {

            }
        };


        recyclerViewColor.addItemDecoration(new RecyclerView.ItemDecoration() {
            @Override
            public void onDraw(Canvas c, RecyclerView parent, RecyclerView.State state) {
                super.onDraw(c, parent, state);
            }

            @Override
            public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
                super.getItemOffsets(outRect, view, parent, state);
                outRect.bottom = 10;
                outRect.right = 10;
            }
        });
        recyclerViewSize.addItemDecoration(new RecyclerView.ItemDecoration() {
            @Override
            public void onDraw(Canvas c, RecyclerView parent, RecyclerView.State state) {
                super.onDraw(c, parent, state);
            }

            @Override
            public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
                super.getItemOffsets(outRect, view, parent, state);
                outRect.bottom = 10;
                outRect.right = 10;
            }
        });
        tv_price.setText("¥ " + price);
        tv_remain.setText("库存" + remain + "件");
        ImageLoaderHelper.getInstance().GlideImageLoader(getActivity(), url, img_goods);

        return view;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    @NonNull
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        mDialog = super.onCreateDialog(savedInstanceState);
        mDialog.setCancelable(false);
        Window window = mDialog.getWindow();
        if (window != null) {
            window.setGravity(Gravity.BOTTOM);
//            window.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
//            window.setLayout(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        }
        return mDialog;
    }


    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        getDialog().getWindow().requestFeature(Window.FEATURE_NO_TITLE);
        super.onActivityCreated(savedInstanceState);
        getDialog().getWindow().setBackgroundDrawable(new ColorDrawable(0x00000000));
        getDialog().getWindow().setLayout(WindowManager.LayoutParams.MATCH_PARENT, WindowManager.LayoutParams.WRAP_CONTENT);
    }


    public boolean isShowing() {
        return mDialog != null && mDialog.isShowing();
    }


    public OnItemClickListener getmListener() {
        return mListener;
    }

    public void setmListener(OnItemClickListener mListener) {
        this.mListener = mListener;
    }

    public interface OnItemClickListener {
        void onConfirm(String name);
    }


    public void getAllSize(String goodsid) {
        RestProxy.getInstance().getAllSize(goodsid, new Observer<StyleResponse>() {
            @Override
            public void onSubscribe(Disposable d) {

            }

            @Override
            public void onNext(StyleResponse styleResponse) {
                listColor.clear();
                listColor.addAll(styleResponse.map.colors);
                for (int i = 0;i<listColor.size();i++){
                    listColor.get(i).select = -1;
                }
                listSize.clear();
                listSize.addAll(styleResponse.map.sizes);
                adapterColor.notifyDataSetChanged();
                adapterSize.notifyDataSetChanged();
            }

            @Override
            public void onError(Throwable e) {

            }

            @Override
            public void onComplete() {

            }
        });
    }


    private void queryGoodsId(String style_color) {

        RestProxy.getInstance().queryGoodsId(PreferencesHelper.getInstance().getString(getActivity(),"token"),goodsid, style_color, new Observer<StyleResponse>() {
            @Override
            public void onSubscribe(Disposable d) {

            }

            @Override
            public void onNext(StyleResponse styleResponse) {
                for (int j = 0; j < listColor.size(); j++) {
                    listColor.get(j).select = -1;
                }


                for (int i = 0; i < styleResponse.map.colorsBySize.size(); i++) {
                    for (int j = 0; j < listColor.size(); j++) {
                        if (listColor.get(j).style_color.equals(styleResponse.map.colorsBySize.get(i).style_color)) {
                            listColor.get(j).select = 0;
                            listColor.get(j).goods_style_id = styleResponse.map.colorsBySize.get(i).goods_style_id;
                            listColor.get(j).goods_inventory = styleResponse.map.colorsBySize.get(i).goods_inventory;
                            listColor.get(j).style_price = styleResponse.map.colorsBySize.get(i).style_price;
                            listColor.get(j).goods_icon = styleResponse.map.colorsBySize.get(i).goods_icon;
                            listColor.get(j).style_icon = styleResponse.map.colorsBySize.get(i).style_icon;
                        }
                    }
                }


                adapterColor.notifyDataSetChanged();

            }

            @Override
            public void onError(Throwable e) {

            }

            @Override
            public void onComplete() {

            }
        });
    }


    private void addShoppingCar(String goods_style_id, String goods_num) {
        String remains = tv_remain.getText().toString();
        String num = "";
        for(int i = 2 ;i<remains.length();i++){
            String s = remains.substring(i,i+1);
            try {
                Integer.parseInt(s);
                num = num + s;
            } catch (NumberFormatException err) {
            }
        }
        if(Integer.valueOf(goods_num)>Integer.valueOf(num)){
            Toast.makeText(getActivity(), "该宝贝不能购买更多呦", Toast.LENGTH_SHORT).show();
            return;
        }
        RestProxy.getInstance().addShoppingCar(PreferencesHelper.getInstance().getString(getActivity(),"token"), "1", goods_style_id, goods_num, new Observer<BaseResponse>() {
            @Override
            public void onSubscribe(Disposable d) {

            }

            @Override
            public void onNext(BaseResponse baseResponse) {
                Toast.makeText(getActivity(), "添加成功，在购物车等亲", Toast.LENGTH_SHORT).show();
                dismiss();
            }

            @Override
            public void onError(Throwable e) {
                if (e instanceof BusinessException) {
                    ((BaseActivity) getActivity()).toLogin(((BusinessException) e).errorCode);
                }
            }
            @Override
            public void onComplete() {

            }
        });
    }

    public void setData(String price, String remain, String url) {
        this.price = price;
        this.remain = remain;
        this.url = url;
    }
}
